package com.rain.shoppingscienceproj.ui.activity.pay;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.WeChatPayBean;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.order.FinishPayOrderActivity;
import com.rain.shoppingscienceproj.ui.activity.order.MakeOrderActivity;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.PayResult;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PayActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_order_num)
    TextView tv_order_num;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.iv_wxpay)
    ImageView iv_wxpay;
    @BindView(R.id.iv_pay)
    ImageView iv_pay;
    int payType = 0;//1微信支付/2支付宝支付
    private IWXAPI api;
    private String orderId = "", pay = "";

    int type = 0;

    private static final int TIMELINE_SUPPORTED_VERSION = -1;
    private static final int TIMELINE_SUPPORTED_VERSIONS = 0;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        startActivitys(FinishPayOrderActivity.class, TIMELINE_SUPPORTED_VERSIONS);
                        ToastUtils.showShortToast("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShortToast("支付失败");
                        startActivitys(FinishPayOrderActivity.class, TIMELINE_SUPPORTED_VERSION);
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pay);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        tv_title.setText("支付");
        loadingDialog = new LoadingDialog(this, "正在加载...");
        orderId = getIntent().getStringExtra("type");
        pay = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("status", 0);
        api = WXAPIFactory.createWXAPI(this, "wx1667701a1c1857aa");
        api.registerApp("wx1667701a1c1857aa");
        double money = Double.valueOf(pay) / 100;
        tv_money.setText("¥" + money);
        tv_order_num.setText(orderId);
    }

    @OnClick(R.id.rl_back)
    void rlback() {
        back();
    }

    @OnClick(R.id.ll_wx_pay)
    void wxPay() {
        payType = 1;
        iv_wxpay.setImageResource(R.drawable.address_complete);
        iv_pay.setImageResource(R.drawable.wallet_recharge_checkbox);
    }

    @OnClick(R.id.ll_pay)
    void pay() {
        payType = 2;
        iv_pay.setImageResource(R.drawable.address_complete);
        iv_wxpay.setImageResource(R.drawable.wallet_recharge_checkbox);
    }


    @OnClick(R.id.btn_pay)
    void subPay() {
        if (payType == 0) {
            ToastUtils.showShortToast("请选择支付方式");
            return;
        }

        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("type", type + "");
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .pay(map, new BaseSubscriber<WeChatPayBean>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        loadingDialog.dismiss();
                        DialogUtils.dialogRegis(PayActivity.this, e.Message);
                        DialogUtils.getTv_sure().setOnClickListener(view -> {
                            DialogUtils.dismissDialog();
                        });
                    }

                    @Override
                    public void onNext(WeChatPayBean payData) {
                        super.onNext(payData);
                        loadingDialog.dismiss();
                        GlobalData.setOrderId(payData.getOrderId());
                        GlobalData.setStatus(2);
                        if (payType == 1) {
                            PayReq req = new PayReq();
                            req.appId = payData.getAppid();
                            req.partnerId = payData.getPartnerid();
                            req.prepayId = payData.getPrepayid();
                            req.packageValue = "Sign=WXPay";
                            req.nonceStr = payData.getNoncestr();
                            req.timeStamp = payData.getTimestamp() + "";
                            req.sign = payData.getSign();
                            api.sendReq(req);
                        } else {
                            Runnable payRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    PayTask alipay = new PayTask(PayActivity.this);
                                    Map<String, String> result = alipay.payV2(payData.getSign(), true);
                                    Message msg = new Message();
                                    msg.what = 1;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            };
                            // 必须异步调用
                            Thread payThread = new Thread(payRunnable);
                            payThread.start();
                        }
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            back();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }

    private void back() {
        DialogUtils.dialog(PayActivity.this, "订单已经生成确定返回吗？");
        DialogUtils.getTv_sure().setOnClickListener(view -> {
            DialogUtils.dismissDialog();
            finish();
        });
    }

}
